package dotdashdot.bradz.trendsettr;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;



public class ActivityStartTrend extends Activity {
	
	private ClassFonts fonts;
	private TextView search_text;
	//private Bundle extras;
	
	//This is for saving things to the app
	private ClassTrendingContainer container;
	private ClassUserCredentials credentials;
	
	//
	private Context context;
	
	//This is for sending things to the server
	private ClassNetworkHelper helper;
	private ApplicationGlobalVars globals;
	private ProgressBar progress;
	private LinearLayout search_area;
	private EditText text_box;
	private ClassUberLogger logger;
	
	Handler myHandler = new Handler() {

  	    @Override
  	    public void handleMessage(Message msg) {
  	        switch (msg.what) {
  	        case 0:
  	        	create_buttons();
  	            break;
  	        case 5:
	        	format_credentials();
	        	break;
  	        default:
  	            break;
  	        }
  	    }
  	};
  	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start_trend);
		logger = new ClassUberLogger("ActivityStartTrend");
		context = this;
		container = new ClassTrendingContainer();
		fonts = new ClassFonts(this.getAssets());
		
		search_text = (TextView) this.findViewById(R.id.start_trend_upper_text);
		search_area = (LinearLayout) this.findViewById(R.id.trend_layout_inner_button);
		text_box = (EditText) this.findViewById(R.id.start_trend_edit_box);
		progress = (ProgressBar) this.findViewById(R.id.progress_start);

		search_text.setTypeface(fonts.get_font("book"));
		helper = new ClassNetworkHelper(this,((ApplicationGlobalVars) this.getApplication()));
		
		globals = ((ApplicationGlobalVars) this.getApplication());
		
		credentials = new ClassUserCredentials(globals);
		if(!credentials.logged_in){
			apply_for_credentials();
		}else{
			format_credentials();
		}
		format_nav_tab();
		
    	logger.info("OnCreate finished");
	}
	
	private void apply_for_credentials(){
		set_loading_elements(true);
		helper.apply_for_credentials(credentials, myHandler);
	}
	
	private void set_loading_elements(boolean loading_something){
		if(loading_something){
			search_text.setVisibility(View.INVISIBLE);
			search_area.setVisibility(View.INVISIBLE);
			text_box.setVisibility(View.INVISIBLE);
			progress.setVisibility(View.VISIBLE);
	    	logger.info("Still loading...");
		}else{
			search_text.setVisibility(View.VISIBLE);
			search_area.setVisibility(View.VISIBLE);
			text_box.setVisibility(View.VISIBLE);
			progress.setVisibility(View.INVISIBLE);
	    	logger.info("Done loading");
		}
	}
	
  	private void format_nav_tab(){
		final TextView navigation_text = (TextView) findViewById(R.id.top_navigation_text);
		navigation_text.setTypeface(fonts.get_font("cond_medium"));
    	logger.info("Nav tab formatted");
	}
  	
  	private void format_credentials(){
  		set_loading_elements(true);
    	TextView user_name_text_view = (TextView) this.findViewById(R.id.user_name_footer);
    	TextView user_rank_text_view = (TextView) this.findViewById(R.id.user_rank_footer);
    	user_name_text_view.setTypeface(fonts.get_font("medium_italic"));
    	user_rank_text_view.setTypeface(fonts.get_font("medium"));
    	user_name_text_view.setText(credentials.name);
    	user_rank_text_view.setText("Trendsettr Rank: "+credentials.rank);
    	globals.set_credentials_store(credentials);
		helper.get_all_from_network_see_trend(container, myHandler);
    	logger.info("Credentials formatted");
    }
	
    @Override
    public void onResume(){
    	super.onResume();
    	container = new ClassTrendingContainer();
    	if(!credentials.logged_in && !helper.applying()){
    		apply_for_credentials();
		}else if(!helper.applying()){
			format_credentials();
		}
    	logger.info("OnResume finished");
    }
    
	public void create_buttons(){
		final Button search_button = (Button) findViewById(R.id.start_trend_search_button);
		final ClassAlerts alert = new ClassAlerts(context,"","",text_box);
		
		set_loading_elements(false);
		
		search_button.setTypeface(fonts.get_font("bold"));
		search_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
		    	logger.info("Search Clicked!!!");
            	String new_topic = "New";
            	String new_trend = text_box.getText().toString();
		    	logger.info("Text Value: " + new_trend);
            	if(new_trend.length()>0){
            		container.add_topic(new_topic);
            		boolean contains_trend = container.get_topic(new_topic).contains_trend(new_trend);
            		boolean close_to_trend = container.get_topic(new_topic).close_to_trend(new_trend, new_trend.length()/10);
            		boolean too_many_letters = new_trend.length() >= 160;
            		boolean invalid_characters = new_trend.contains("/");
            		//close_to_trend
            		if(!contains_trend && !close_to_trend && !too_many_letters && !invalid_characters){
            			container.get_topic(new_topic).add_trend(credentials.profile_pic,new_trend, "Meta Summary", "google.com",0,0,new Timestamp(0));
        		    	logger.info("No errors found in string. Submitting trend...");
		            	
		            	List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		        		pairs.add(new BasicNameValuePair("topicName", StringUtils.capitalize(new_topic)));
		        		pairs.add(new BasicNameValuePair("trendName", StringUtils.capitalize(new_trend)));
		        		
		        		//helper.post_network(pairs, "/topic");
		        		helper.post_network(pairs, "/trend", myHandler);
		            	
		            	new AlertDialog.Builder(context)
		                .setTitle("Trend Submitted!")
		                .setMessage("Your trend has been submitted and will now be evaluated by our team of crack specialists.")
		                .setPositiveButton("Contiue", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int which) { 
		                        // continue with delete
		                    	text_box.setText("");
		                    }
		                 })
		                 .show();
            		}else{
            			if(contains_trend){
            				
            				alert.set_title("Trend Duplicate!");
            				alert.set_message("This trend has already been submitted!");
            				alert.show_message(false);
            				
            		    	logger.warning("Trend Duplicate! This trend has already been submitted!");
            				
            			}else if(close_to_trend){
            				
            				alert.set_title("Trend Too Close!");
            				alert.set_message("This trend is too close to a current trend!");
            				alert.show_message(false);
            				
            				logger.warning("Trend Too Close! This trend is too close to a current trend!");
            				
            			}else if(invalid_characters){
            				
            				alert.set_title("Bad Characters!");
            				alert.set_message("This trend has one or more invalid characters!");
            				alert.show_message(false);
            				
            				logger.warning("Bad Characters! This trend has one or more invalid characters!");
            				
            			}else{
            				
            				alert.set_title("Too Many Letters!");
            				alert.set_message("This trend contains more than 160 characters!");
            				alert.show_message(false);
            				
            				logger.warning("Too Many Letters! This trend contains more than 160 characters!");

            			}
            		}
            	}
            }
        });
	}

}
